package top.chengdongqing.mishop.common.security

import jakarta.servlet.FilterChain
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.apache.logging.log4j.LogManager
import org.springframework.http.HttpHeaders
import org.springframework.security.authentication.AuthenticationManager
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter
import org.springframework.stereotype.Component

@Component
class JwtAuthenticationFilter(authenticationManager: AuthenticationManager) :
    BasicAuthenticationFilter(authenticationManager) {
    private val log = LogManager.getLogger(JwtAuthenticationFilter::class.java)

    override fun doFilterInternal(request: HttpServletRequest, response: HttpServletResponse, chain: FilterChain) {
        val token = request.getHeader(HttpHeaders.AUTHORIZATION)
        if (token.isNullOrBlank() || !token.startsWith("Bearer ")) {
            chain.doFilter(request, response)
            return
        }

        val pureToken = token.substring(7) // 去除 “Bearer ” 前缀
        val authenticationToken = UsernamePasswordAuthenticationToken(pureToken, null)

        try {
            val authenticate = authenticationManager.authenticate(authenticationToken)
            SecurityContextHolder.getContext().authentication = authenticate
        } catch (e: Exception) {
            log.warn("无效令牌: {}", pureToken)
        }

        chain.doFilter(request, response)
    }
}